package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private  Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");
        //解析select标签
        List<Element> selectlist = rootElement.selectNodes("//select");
        Elementforeach(selectlist,namespace);
        //解析insert标签
        List<Element> insertlist = rootElement.selectNodes("//insert");
        Elementforeach(insertlist,namespace);
        //解析update标签
        List<Element> updatelist = rootElement.selectNodes("//update");
        Elementforeach(updatelist,namespace);
        //解析delete标签
        List<Element> deletelist = rootElement.selectNodes("delete");
        Elementforeach(deletelist,namespace);

    }
    public void Elementforeach(List<Element> list, String namespace){
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(parameterType);
            mappedStatement.setSql(sqlText);
            String key = namespace+"."+id;
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }
    }
}
